// app.js
App({
  globalData: {
    userInfo: null,
    playingBook: null,
    playStatus: 'paused',
    playProgress: 0,
    audioContext: null,
    bookList: [
      {
        id: 1,
        title: "活着",
        author: "余华",
        cover: "https://picsum.photos/200/300?random=1",
        duration: "12小时30分钟",
        episodes: [
          { id: 101, title: "第一章", url: "audio/chapter1.mp3", duration: "30:25" },
          { id: 102, title: "第二章", url: "audio/chapter2.mp3", duration: "28:40" }
        ]
      },
      {
        id: 2,
        title: "平凡的世界",
        author: "路遥",
        cover: "https://picsum.photos/200/300?random=2",
        duration: "24小时15分钟",
        episodes: [
          { id: 201, title: "第一部 第一章", url: "audio/t1c1.mp3", duration: "35:10" },
          { id: 202, title: "第一部 第二章", url: "audio/t1c2.mp3", duration: "32:45" }
        ]
      }
    ]
  },
  onLaunch() {
    this.initApp().catch(err => console.error('初始化应用错误:', err));
  },
  onHide() {
    const { audioContext } = this.globalData;
    if (audioContext) {
      audioContext.pause();
    }
  },
  
  onUnload() {
    const { audioContext } = this.globalData;
    if (audioContext) {
      audioContext.destroy();
      this.globalData.audioContext = null;
    }
  },
  playNextEpisode() {
    // 播放下一集的逻辑实现
  },
  initApp() {
    return new Promise(resolve => {
      // 模拟异步初始化过程，实际只需要延迟执行
      setTimeout(() => {
        this.initAudioContext();
        resolve();
      }, 1500);
    });
  },
  initAudioContext() {
    // 初始化音频上下文
    this.globalData.audioContext = wx.createInnerAudioContext();
    this.globalData.audioContext.onPlay(() => {
      this.globalData.playStatus = 'playing';
    });
    this.globalData.audioContext.onPause(() => {
      this.globalData.playStatus = 'paused';
    });
    this.globalData.audioContext.onEnded(() => {
      this.globalData.playStatus = 'ended';
      // 自动播放下一集逻辑
      this.playNextEpisode();
    });
    this.globalData.audioContext.onTimeUpdate(() => {
      this.globalData.playProgress = this.globalData.audioContext.currentTime / this.globalData.audioContext.duration;
    });
  },
  // 设置播放速度
setPlaybackRate(rate) {
  const { audioContext } = this.globalData;
  if (audioContext) {
    audioContext.playbackRate = rate;
  }
},

// 设置音量
setVolume(volume) {
  const { audioContext } = this.globalData;
  if (audioContext) {
    audioContext.volume = volume;
  }
}
})
    